package session

import (
	"data-transfer/conf"
	_ "github.com/go-sql-driver/mysql"
	"xorm.io/xorm"
	"xorm.io/xorm/names"
)

var DefaultDBUrl = "localhost:3306"

type Session struct {
	*xorm.Engine
}

// NewSession 创建新的Session对象，Warpper xorm.Engine 对象
func NewSession(cfg *conf.DbConfig, dbName string) (*Session, error) {
	engine, err := createConnection(cfg, dbName)
	if err != nil {
		return nil, err
	}
	return &Session{engine}, nil
}

// Close 关闭这个倒霉玩意
func (s *Session) Close() {
	if s.Engine != nil {
		_ = s.Engine.Close()
	}
}

func createConnection(cfg *conf.DbConfig, dbName string) (*xorm.Engine, error) {
	var dbUrl string
	var err error
	var engine *xorm.Engine

	//每一个DBName 对应一个 Engine
	dbConfInfoMap := cfg.DB
	for name, info := range dbConfInfoMap {
		if name == dbName {
			dbUrl = info.ConnectAddr
			maxOpenConns := info.MaxOpenConns
			maxIdleConns := info.MaxIdleConns
			engine, err = xorm.NewEngine("mysql", dbUrl)
			if err == nil {
				engine.SetMaxIdleConns(maxIdleConns)
				engine.SetMaxOpenConns(maxOpenConns)
			}
			// 设置表名命名规则映射方案
			engine.SetTableMapper(names.SameMapper{})
			// 默认为SnakeMapper
			//engine.SetColumnMapper(names.SnakeMapper{})
			break
		}
	}

	return engine, err
}
